import React, { useEffect, useRef, useState } from 'react'
import { Col, Row, Form, Input, Button, Table, Select, Space, Modal, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { formatDate } from '@/utils'
import { getUsersList, deleteUser } from '@/api/user'
import { IUserItem } from '@/types/user'
import CreateUser from './components/CreateUser'
import { ModelAction } from '@/types/modal'

const UserList: React.FC = () => {
  const [tableData, setTableData] = useState<IUserItem[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 5
  })

  const [form] = Form.useForm()
  const createUserRef = useRef<{ open: (type: ModelAction, data?: IUserItem) => void }>()

  useEffect(() => {
    fetchData(pagination.pageNum, pagination.pageSize)
  }, [])

  const fetchData = async (pageNum: number, pageSize: number) => {
    setLoading(true)
    const formData = form.getFieldsValue()
    const {
      data: { list, page }
    } = await getUsersList({
      ...formData,
      pageNum,
      pageSize
    })
    setLoading(false)
    setTableData(list)
    setTotal(page.total)
  }
  // 条件搜索
  const handleSearch = () => {
    setPagination({ pageNum: 1, pageSize: 5 })
    fetchData(1, 5)
  }

  // 重置
  const handleReset = () => {
    form.resetFields()
    setPagination({ pageNum: 1, pageSize: 5 })
    fetchData(1, 5)
  }
  // 新增
  const handleCreateUser = () => {
    createUserRef.current?.open('create')
  }
  // 编辑
  const handleEdit = (record: IUserItem) => {
    createUserRef.current?.open('edit', record)
  }
  // 删除
  const handleDel = (userId: number) => {
    Modal.confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: <span>确定删除吗？</span>,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        handleDelUser([userId])
      }
    })
  }
  // 批量删除
  const handleBatchDelete = () => {
    Modal.confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: <span>确定删除吗？</span>,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        handleDelUser(selectedRowKeys)
      }
    })
  }

  const handleDelUser = (userIds: number[]) => {
    deleteUser(userIds).then(() => {
      message.success('删除成功')
      fetchData(1,5)
      setSelectedRowKeys([])
    })
  }
  const columns: ColumnsType<IUserItem> = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId'
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '用户邮箱',
      dataIndex: 'userEmail',
      key: 'userEmail'
    },
    {
      title: '用户角色',
      dataIndex: 'role',
      key: 'role',
      render(role: number) {
        return {
          0: '超级管理员',
          1: '管理员',
          2: '体验管理员',
          3: '普通用户'
        }[role]
      }
    },
    {
      title: '用户状态',
      dataIndex: 'state',
      key: 'state',
      render(state: number) {
        return {
          1: '在职',
          2: '离职',
          3: '试用期'
        }[state]
      }
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render(createTime: string) {
        return formatDate(createTime)
      }
    },
    {
      title: '操作',
      key: 'address',
      render(record) {
        return (
          <Space>
            <Button type='text' onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type='text' danger onClick={() => handleDel(record.userId)}>
              删除
            </Button>
          </Space>
        )
      }
    }
  ]
  return (
    <div className='list_page'>
      <div className='list_page__header'>
        <Form form={form} initialValues={{ state: 1 }}>
          <Row gutter={10}>
            <Col lg={6} xs={24} sm={12}>
              <Form.Item label='用户ID' name='userId'>
                <Input />
              </Form.Item>
            </Col>
            <Col lg={6} xs={24} sm={12}>
              <Form.Item label='用户名称' name='userName'>
                <Input />
              </Form.Item>
            </Col>
            <Col lg={6} xs={24} sm={12}>
              <Form.Item name='state' label='状态'>
                <Select>
                  <Select.Option value={0}>所有</Select.Option>
                  <Select.Option value={1}>在职</Select.Option>
                  <Select.Option value={2}>离职</Select.Option>
                  <Select.Option value={3}>试用期</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col lg={6} xs={24} sm={12}>
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button type='primary' style={{ marginRight: 8 }} onClick={handleSearch}>
                  搜索
                </Button>
                <Button onClick={handleReset}>重置</Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
      <div className='list_page__wrapper'>
        <div className='list_page__wrapper__toolbar'>
          <div className='list_page__wrapper__toolbar__title'>用户列表</div>
          <div className='list_page__wrapper__toolbar__right'>
            <Button type='primary' style={{ marginRight: 8 }} onClick={handleCreateUser}>
              新增
            </Button>
            <Button type='primary' danger onClick={handleBatchDelete}>
              批量删除
            </Button>
          </div>
        </div>
        <div>
          <Table
            loading={loading}
            columns={columns}
            dataSource={tableData}
            rowKey='userId'
            rowSelection={{
              type: 'checkbox',
              selectedRowKeys,
              onChange(selectedRowKeys) {
                setSelectedRowKeys(selectedRowKeys as number[])
              }
            }}
            pagination={{
              position: ['bottomRight'],
              total,
              current: pagination.pageNum,
              pageSize: pagination.pageSize,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSizeOptions: [5, 10, 20, 50],
              showTotal: function (total) {
                return `总共：${total}条`
              },
              onChange: (page, pageSize) => {
                setPagination({
                  pageNum: page,
                  pageSize
                })
                fetchData(page, pageSize)
              }
            }}
          ></Table>
        </div>
      </div>
      <CreateUser
        mRef={createUserRef}
        update={() => {
          fetchData(1, 5)
        }}
      />
    </div>
  )
}

export default UserList
